import agreec from "./agreeC.js"
//66+0000000000000000(mac)+05(总数据长度)+00000000(4字节随机数)+00(命令码)+000000000000(参数弹性字节数)+00(校验位1字节)
var verify = function(upData) {
	return agreec.verify(upData)
}

var down = function(mac, command, param) {
	return agreec.down(mac, command, param);
}
var downData = function(mac, command, random, param, check) {
	return agreec.downData(mac, command, random, param, check);
}

var intToHex = function(val) {
	var hex = parseInt(val).toString(16);
	return hex;
}
var hexToInt = function(hex) {
	var val = parseInt(hex, 16);
	return val;
}


var takeHex = function(hex, off, length) {
	return agreec.takeHex(hex, off, length);
}

function randomNum(minNum, maxNum) {
	return agreec.randomNum(minNum, maxNum);
}
//累加校验和 累加之后取低字节
var makeChecksum = function(data) {
	if (data == null || data == "") {
		return "";
	}
	if (data.length % 2 != 0) {
		return "";
	}
	var total = 0;
	var len = data.length;
	var num = 0;
	while (num < len) {
		var s = data.substring(num, num + 2);
		total += hexToInt(s);
		num = num + 2;
	}

	var mod = total % 256;
	var hex = intToHex(mod);
	len = hex.length;
	if (len < 2) {
		hex = "0" + hex;
	}
	return hex;
}

var getF0 = function(mac) {
	var data = down(mac, "F0", "");
	return data;
}
var get08 = function(mac) {
	var data = down(mac, "08", "");
	return data;
}

var get02 = function(mac, type, userId, carId) {
	mac = padLeft(mac, "0", 16);
	userId = padLeft(userId, "0", 8);
	carId = padLeft(carId, "0", 8);
	type = padLeft(type, "0", 2);
	var param = type + userId + carId;
	var data = down(mac, "02", param);
	return data;
}

/**
 * 下料（考虑到多平台，终端用明文，不用密文）
 * @param {*} mac 
 * @param {*} type 1授权清除并使用  2清除数据
 * @param {*} userId 
 * @param {*} carId 
 * @param {*} balance 色号
 * @param {*} consume 用量
 * @param {*} deviceTranNo 流水号
 * @param {*} mode 模式 1大师模式 2是智能模式 默认智能模式
 */
var get06 = function(mac, type, userId, carId, balance, consume, deviceTranNo, mode) {
	userId = userId == undefined ? "" : parseInt(userId).toString(16);

	userId = padLeft(userId, "0", 8);
	// console.log("agreement get06----->userId2: ", userId);
	type = type == undefined ? "" : parseInt(type).toString(16);
	// console.log("agreement get06----->type1: ", type);
	type = padLeft(type, "0", 2);
	// console.log("agreement get06----->type2: ", type);
	carId = carId == undefined ? "" : carId;
	// console.log("agreement get06----->carId1: ", carId);
	carId = padLeft(carId, "0", 8);
	// console.log("agreement get06----->carId2: ", carId);
	balance = balance == undefined ? "" : parseInt(balance).toString(16);
	// console.log("agreement get06----->balance1: ", balance, typeof balance);
	var modeHex = "00"; //AA大师模式  AB是智能模式（染膏）
	if (mode == 1) {
		modeHex = "AB";
	} else if (mode == 2) {
		modeHex = "AA";
	}


	balance = modeHex + padLeft(balance, "0", 6);
	// console.log("agreement get06----->balance2: ", balance, typeof balance);
	consume = consume == undefined ? "" : parseInt(consume).toString(16);
	// console.log("agreement get06----->consume1: ", consume, typeof consume);
	consume = padLeft(consume, "0", 4);
	// console.log("agreement get06----->consume2: ", consume, typeof consume);
	deviceTranNo = deviceTranNo == undefined ? "" : deviceTranNo + "";
	// console.log("agreement get06----->deviceTranNo1: ", deviceTranNo);
	deviceTranNo = padLeft(deviceTranNo, "0", 4);
	// console.log("agreement get06----->deviceTranNo2: ", deviceTranNo);
	var dateStr = dateFormat(new Date());

	let map = {};

	var decryptData = userId + carId + balance + consume + deviceTranNo;
	// console.log("userId -----> ", userId, userId.length);
	// console.log("carId -----> ", carId, carId.length);
	// console.log("balance -----> ", balance, balance.length);
	// console.log("consume -----> ", consume, consume.length);
	// console.log("deviceTranNo -----> ", deviceTranNo, deviceTranNo.length);
	var param = type + decryptData + dateStr;
	// console.log("agreement get06 param -----> ", param);
	// console.log("type -----> ", type);
	// console.log("decryptData -----> ", decryptData, decryptData.length);
	// console.log("dateStr -----> ", dateStr, dateStr.length);
	var data = down(mac, "06", param);
	// console.log("agreement get06 down -------->", JSON.stringify(data));
	map.data = data;
	map.decryptData = decryptData;
	map.param = param;
	map.useTime = dateStr;

	console.log("agreement get06===userId=" + userId + ";modeHex=" +
		modeHex + ";balance(色号)=" + balance + ";consume(用量)=" + consume);

	return map;
}

/**
 * 下料（考虑到多平台，终端用明文，不用密文）
 * @param {*} mac 
 * @param {*} type 1授权清除并使用  2清除数据
 * @param {*} userId 
 * @param {*} carId 
 * @param {*} balance 色号
 * @param {*} consume 用量
 * @param {*} deviceTranNo 流水号
 * @param {*} mode 模式 1大师模式 2是智能模式 默认智能模式
 * @param {*} cList 几个头 [{1:1},{3:10},{5:19}]
 */
var get16 = function(mac, type, userId, carId, balance, consume, deviceTranNo, mode, cList) {
	console.log("进入get16: ");
	userId = userId == undefined ? "" : parseInt(userId).toString(16);

	userId = padLeft(userId, "0", 8);
	type = type == undefined ? "" : parseInt(type).toString(16);
	type = padLeft(type, "0", 2);
	carId = carId == undefined ? "" : carId;
	carId = padLeft(carId, "0", 8);
	balance = balance == undefined ? "" : parseInt(balance).toString(16);
	var modeHex = "00"; //AA大师模式  AB是智能模式（染膏）
	if (mode == 1) {
		modeHex = "AB";
	} else if (mode == 2) {
		modeHex = "AA";
	}


	balance = modeHex + padLeft(balance, "0", 6);
	consume = consume == undefined ? "" : parseInt(consume).toString(16);
	consume = padLeft(consume, "0", 4);
	deviceTranNo = deviceTranNo == undefined ? "" : deviceTranNo + "";
	deviceTranNo = padLeft(deviceTranNo, "0", 4);
	var dateStr = dateFormat(new Date());

	let map = {};


	var count = 0;
	var cParam = "";
	console.log("cList==============================================>", cList)
	cList.forEach(item => {
		Object.keys(item).forEach(key => {
			var hexI = agreec.intToHex(parseInt(key));
			hexI = hexI.padStart(2, '0');
			var tiemVal = (item[key] + '').split('.');
			var inter = 0;
			var floter = 0;
			if (tiemVal.length > 1) {
				inter = parseInt(tiemVal[0]);
				floter = parseInt(tiemVal[1]);
				console.log(inter, floter)
			} else {
				inter = parseInt(tiemVal[0]);
			}

			var hexInter = agreec.intToHex(inter);
			var hexFloter = agreec.intToHex(floter);

			hexInter = hexInter.padStart(2, '0');
			hexFloter = hexFloter.padStart(2, '0');
			var hexV = hexInter + hexFloter;

			cParam += hexI + hexV;
			count++;
			console.log('key, cList key', key, item[key]);
		})
	})


	var hexCount = intToHex(count);
	hexCount = padLeft(hexCount, "0", 2);

	console.log('cParam ==============> ', cParam);
	console.log("cList ====================================> ", cList);


	cParam = hexCount + cParam;
	// console.log('cParam', cParam);
	var decryptData = userId + carId + balance + consume + deviceTranNo;
	var param = type + decryptData + dateStr + cParam;

	var data = down(mac, "16", param);
	map.data = data;
	map.decryptData = decryptData;
	map.param = param;
	map.useTime = dateStr;

	console.log("agreement get16===userId=" + userId + ";modeHex=" +
		modeHex + ";balance(色号)=" + balance + ";consume(用量)=" + consume);

	return map;
}


var get14 = function(mac, userId) {
	mac = padLeft(mac, "0", 16);
	userId = padLeft(userId, "0", 16);
	var param = "00" + userId;
	var data = down(mac, "14", param);
	return data;
}

/**
 * 校准/取消校准
 * @param {Object} mac
 * @param {Object} val 0退出校准，1校准
 */
var get07Calibration = function(mac, val) {
	mac = padLeft(mac, "0", 16);

	var hextype = "01"; //01校准/取消校准 02更新色号列表 03更新色号版本
	var hexval = padLeft((val == undefined ? "" : parseInt(val).toString(16)), "0", 2);

	var param = hextype + hexval;
	console.log("get07Calibration=============hextype=" + hextype + " hexval=" + hexval + " val=" + val +
		" param=" + param);
	var data = down(mac, "07", param);
	return data;
}


/**
 * 自动校准/取消校准
 * @param {Object} mac
 */
var get07AutoCalibration = function(mac) {
	console.log("mac1: ",mac);
	var mac = padLeft(mac, "0", 16);
	console.log("mac2: ",mac);

	var hextype = "08"; // 08 自动校准
	var hexval = "01"; //0：无效，1：校准

	var param = hextype + hexval;
	//var data = down(mac, "07", param);
	var data = get07Hex(mac, hextype, hexval);
	return data;
}

/**
 * 设置音量
 * @param {*} mac 
 * @param {*} val 0-5
 */
var get07UpdateVolumn = function(mac, val) {
	var mac = padLeft(mac, "0", 16);
	console.log("val: ",val);
	var hextype = "07"
	var hexval = padLeft((val == undefined ? "" : parseInt(val).toString(16)), "0", 2);
	console.log("hexval: ",hexval);
	var param = hextype + hexval;
	//var data = down(mac, "07", param);
	var data = get07Hex(mac, hextype, hexval);
	return data;
}



/**
 * 换料
 * @param {Object} mac
 * @param {Object} val 1：换料完成，继续运行，2：不换料直接退出
 */
var get07UpdateMaterial = function(mac, val) {
	mac = padLeft(mac, "0", 16);

	var hextype = "04"; // 04 换料
	var hexval = padLeft((val == undefined ? "" : parseInt(val).toString(16)), "0", 2);

	var param = hextype + hexval;
	var data = down(mac, "07", param);
	return data;
}

/** 
 * 升级更换配方
 * @param {Object} mac
 * @param {Object} sn
 * @param {Object} colorNo
 * @param {Object} count
 * @param {Object} c0No
 * @param {Object} c0Val
 * @param {Object} c1No
 * @param {Object} c1Val
 * @param {Object} c2No
 * @param {Object} c2Val
 * @param {Object} c3No
 * @param {Object} c3Val
 * @param {Object} c4No
 * @param {Object} c4Val
 */
var get07UpdateColor = function(mac, sn, colorNo, count, c0No, c0Val, c1No, c1Val, c2No, c2Val, c3No, c3Val, c4No,
	c4Val) {
	mac = padLeft(mac, "0", 16);

	var hexsn = padLeft((sn == undefined ? "" : parseInt(sn).toString(16)), "0", 2);

	var hexcolorNo = padLeft((colorNo == undefined ? "" : parseInt(colorNo).toString(16)), "0", 4);
	var hexcount = padLeft((count == undefined ? "" : parseInt(count).toString(16)), "0", 2);
	var hexc0No = padLeft((c0No == undefined ? "" : parseInt(c0No).toString(16)), "0", 2);
	var hexc0Val = padLeft((c0Val == undefined ? "" : parseInt(c0Val).toString(16)), "0", 2);
	var hexc1No = padLeft((c1No == undefined ? "" : parseInt(c1No).toString(16)), "0", 2);
	var hexc1Val = padLeft((c1Val == undefined ? "" : parseInt(c1Val).toString(16)), "0", 2);

	var hexc2No = padLeft((c2No == undefined ? "" : parseInt(c2No).toString(16)), "0", 2);
	var hexc2Val = padLeft((c2Val == undefined ? "" : parseInt(c2Val).toString(16)), "0", 2);

	var hexc3No = padLeft((c3No == undefined ? "" : parseInt(c3No).toString(16)), "0", 2);
	var hexc3Val = padLeft((c3Val == undefined ? "" : parseInt(c3Val).toString(16)), "0", 2);

	var hexc4No = padLeft((c4No == undefined ? "" : parseInt(c4No).toString(16)), "0", 2);
	var hexc4Val = padLeft((c4Val == undefined ? "" : parseInt(c4Val).toString(16)), "0", 2);

	var hextype = "02"; //01校准/取消校准 02更新色号列表 03更新色号版本

	var param = hextype + hexsn + hexcolorNo + hexcount +
		hexc0No + hexc0Val +
		hexc1No + hexc1Val +
		hexc2No + hexc2Val +
		hexc3No + hexc3Val +
		hexc4No + hexc4Val;
	console.log('mac', mac);
	console.log('hexsn', hexsn);
	console.log('hexcolorNo', hexcolorNo);
	console.log('hexcount', hexcount);
	console.log('hexc0No', hexc0No);
	console.log('hexc0Val', hexc0Val);
	console.log('hexc1No', hexc1No);
	console.log('hexc1Val', hexc1Val);
	console.log('hexc2No', hexc2No);
	console.log('hexc2Val', hexc2Val);
	console.log('hexc3No', hexc3No);
	console.log('hexc3Val', hexc3Val);
	console.log('hexc4No', hexc4No);
	console.log('hexc4Val', hexc4Val);
	param = padLeft(param, "0", 28);
	var data = down(mac, "07", param);
	return data;
}

var get07UpdateColorEnd = function(mac, colorVersion) {
	mac = padLeft(mac, "0", 16);

	var hextype = "03"; //01校准/取消校准 02更新色号列表 03更新色号版本
	var hexColorVersion = padLeft((colorVersion == undefined ? "" : parseInt(colorVersion).toString(16)), "0", 4);

	var param = hextype + hexColorVersion;
	console.log("hexColorVersion=============hextype=" + hextype + " hexColorVersion=" + hexColorVersion +
		" param=" + param);
	var data = down(mac, "07", param);
	return data;
}


/**
 * 设置各种初始值
 * @param {Object} mac
 * @param {Object} hexType
 * 01校准/取消校准 
 * 02更新色号列表 
 * 03更新色号版本
 * 04----换料 值 1字节 1完成换料 2退出
 * 05----设置重量 值 2字节 350-500ml 
 * 06----设置百分比 
 * 07----设置音量 1字节 0-5
 * 08----自动校准 2字节 高位(泵号) 低位(值)-50~50
 * @param {Object} hexVal
 */
var get07Hex = function(mac, hexType, hexVal) {
	mac = padLeft(mac, "0", 16);

	// var k = hexVal = padLeft(parseInt(1).toString(16), "0", 2);
	// var v = hexVal = padLeft(parseInt(35).toString(16), "0", 2);
	// k+v;

	var param = hexType + hexVal;
	console.log("get07Hex=============hexType=" + hexType + " hexVal=" + hexVal +
		" param=" + param);
	var data = down(mac, "07", param);
	console.log("data: ",data);
	return data;
}
/**
 * 设置结果
 * @param {Object} responseVo 
 */
var verify07 = function(responseVo) {
	if (!responseVo) {
		return false;
	}
	var param = responseVo.param;
	var result = agreec.takeHex(param, 9, 1);
	//0 更新成功 1更新失败
	if (result == "00")
		return true;
	return false;
}


/**
 * 0xF2 MAC授权设置
 *
 * @param mac
 * @param productKey   阿里productKey
 * @param deviceSecret 阿里deviceSecret
 * @return
 */
var getF2 = function(mac, productKey, deviceSecret) {

	var pkLength = 0;
	if (!productKey) {
		pkLength = productKey.length / 2;
	}
	var deviceSecretLength = 0;
	if (!deviceSecret) {
		deviceSecretLength = deviceSecret.length / 2;
	}
	mac = padLeft(mac, "0", 16);
	var netKey = "00000000"; //Netkey密钥（服务器密码因子）4字节
	var hexProductKeyLength = padLeft(intToHex(pkLength), "0", 2);
	var hexDeviceSecretLength = padLeft(intToHex(deviceSecretLength), "0", 2);
	console.log('mac -------------------->', mac, mac.length);
	console.log('netKey -------------------->', netKey, netKey.length);
	console.log('hexProductKeyLength -------------------->', hexProductKeyLength, hexProductKeyLength.length);
	console.log('hexDeviceSecretLength -------------------->', hexDeviceSecretLength, hexDeviceSecretLength.length);
	//var param = (mac + " 12345611 AAAAAAAA 01 0B 00 0000000000000000000000").replace(" ", "");
	var paramDecryptData = mac + netKey + "AAAA" + hexProductKeyLength + hexDeviceSecretLength;

	//var paramEncryptData = DES3.encrypt(key, param);//密文
	var param = paramDecryptData + productKey + deviceSecret;
	var data = down(mac, "F2", param);
	return data;
}


/**
 * 控制码0x37设置二维码指令
 *
 * @param mac
 * @param qrcodeInfo
 * @return
 */
var get37 = function(mac, qrcodeInfo) {
	var hexQrcodeInfo = agreec.stringToHex(qrcodeInfo);
	var qrcodeBytes = (hexQrcodeInfo != "" && hexQrcodeInfo != undefined) ? hexQrcodeInfo.length / 2 : 0; //二维码网址长度
	//var hexQrcodeBytes = StringUtils.leftPad(MyHex.intToHex(qrcodeBytes), 2, "0");
	var hexQrcodeBytes = agreec.intToHex(qrcodeBytes);
	hexQrcodeBytes = hexQrcodeBytes.padStart(2, '0');
	var str = hexQrcodeBytes + hexQrcodeInfo;
	var param = str.padEnd(48, '0');
	var data = down(mac, "37", param);
	return data;
}
/**
 * 二维码设置结果
 * @param {Object} btData
 * @result responVo {"code":0,"message":"设置成功"}
 */
var check37Result = function(btData) {
	var responVo = agreec.verify(btData)
	if (responVo.code != 0) {
		return responVo;
	}
	var res = agreec.takeHex(btData, 19, 1); //0 更新成功 1更新失败
	if (res == "00") {
		return responVo;
	}
	responVo.code = 1;
	responVo.message = "设置失败";
	return responVo;
}


function isOk(btData) {
	//console.log("isOk==========收到数据btData:" + btData);
	if (!btData) {
		return false;
	}
	if (btData.length % 2 != 0) {
		// console.log("isOk==========收到数据为单数btData:" + btData);
		return false;
	}
	var hexLength = takeHex(btData, 9, 1);
	if (!hexLength) {
		// console.log("isOk==========收到数据长度无值hexLength:" + hexLength);
		return false;
	}

	var length = hexToInt(hexLength);
	var total = btData.length / 2;
	var result = (total - 11) == length;
	// console.log("isOk==========结果 result=" + result + " length=" + length + " total=" + total);
	return result;
}

var padLeft = function(ret, padChar, len) {
	if (padChar == undefined || padChar == null) {
		padChar = "";
	}
	while (ret.length < len) {
		if (ret.length + padChar.length < len) {
			ret = padChar + ret;
		} else {
			ret = padChar.substring(0, len - ret.length) + ret;
		}

	}
	return ret;
};
var padRight = function(ret, padChar, len) {
	while (ret.length < len) {
		if (ret.length + padChar.length < len) {
			ret += padChar;
		} else {
			ret += padChar.substring(0, len - ret.length);
		}
	}
	return ret;
}
var dateFormat = function(d) {
	//var d = new Date();
	var curr_date = d.getDate();
	var curr_month = d.getMonth() + 1;
	var curr_year = d.getFullYear();
	var curr_hour = d.getHours();
	var curr_minutes = d.getMinutes();
	var curr_seconds = d.getSeconds();
	String(curr_month).length < 2 ? (curr_month = "0" + curr_month) : curr_month;
	String(curr_date).length < 2 ? (curr_date = "0" + curr_date) : curr_date;

	String(curr_hour).length < 2 ? (curr_hour = "0" + curr_hour) : curr_hour;
	String(curr_minutes).length < 2 ? (curr_minutes = "0" + curr_minutes) : curr_minutes;
	String(curr_seconds).length < 2 ? (curr_seconds = "0" + curr_seconds) : curr_seconds;

	var yearStr = String(curr_year);
	yearStr = yearStr.substring(2);
	var yyMMddHHmmss = yearStr + "" + curr_month + "" + curr_date + curr_hour + curr_minutes + curr_seconds;
	return yyMMddHHmmss;
}

function AgreeInfo(mac, command, length, random, param, check) {
	agreec.AgreeInfo(mac, command, length, random, param, check);
}

class ResponseVo {
	constructor(code, message, data) {
		this.code = code;
		this.message = message;
		this.data = data;
	}
	static success(data) {
		this.code = 0;
		this.message = "";
		this.data = data;
		return new ResponseVo(this.code, this.message, this.data);
	}
	static error(message) {
		this.code = 1;
		this.message = message;
		this.data = null;
		return new ResponseVo(this.code, this.message, this.data);
	}
}



module.exports = {
	down: down,
	verify: verify,
	intToHex: intToHex,
	hexToInt: hexToInt,
	takeHex: takeHex,
	getF0: getF0,
	get08: get08,
	get02: get02,
	getF2: getF2,
	get06: get06,
	get14: get14,
	get16: get16,
	get37: get37,
	padLeft: padLeft,
	get07Hex: get07Hex,
	get07Calibration: get07Calibration,
	get07AutoCalibration: get07AutoCalibration,
	get07UpdateVolumn: get07UpdateVolumn,
	get07UpdateColor: get07UpdateColor,
	get07UpdateColorEnd: get07UpdateColorEnd,
	get07UpdateMaterial: get07UpdateMaterial,
	isOk: isOk,
}

/*Obfuscated by http://tool.chinaz.com/tools/jscodeconfusion.aspx*/
//加密工具已经升级了一个版本，目前为 jsjiami.com.v6
